package org.epidroid.epidroid.news.engine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.james.mime4j.codec.DecoderUtil;
import org.epidroid.epidroid.news.ui.NewsActivity;

import android.util.Log;

public class Topic {
	private List<NewsArticle> _articles = null;
	private String _subject = null;
	private String _serv_id = null;
	private String _group_title = null;
	private HashMap<String, NewsArticle> _map = null;

	public Topic(String groupTitle, String subject, String servId) {
		_map = new HashMap<String, NewsArticle>();
		_serv_id = servId;
		_group_title = groupTitle;
		try {
			_subject = DecoderUtil.decodeEncodedWords(subject, null);
		} catch (Exception e) {
			Log.v(NewsActivity.LOGCAT, e.getMessage());
			_subject = subject;
		}
		_articles = new ArrayList<NewsArticle>();
	}

	/**
	 * At that point, we only have one NewsArticle in the list, but each article
	 * has now a list of pointers to its successors. So, by browsing those
	 * articles we can add every reply in the list
	 */
	public void addRepliesToList() {
		if (_articles.size() == 0)
			return;
		addRepliesToListRec(_articles.get(0));
	}

	private void addRepliesToListRec(NewsArticle article) {
		List<NewsArticle> replies = article.getReplies();
		for (NewsArticle a : replies) {
			if (addArticle(a)) {
				addRepliesToListRec(a);
			}
		}
	}

	public Boolean addArticle(NewsArticle article) {
		// Check if the article already exists
		if (null == _map.get(article.getId())) {
			_articles.add(article);
			_map.put(article.getId(), article);
			return true;
		}
		return false;
	}

	public NewsArticle getArticleByIndex(int index) {
		return _articles.get(index);
	}

	public String getServId() {
		return _serv_id;
	}
	
	public String getSubject() {
		return _subject;
	}
	
	public String getGroupTitle() {
		return _group_title;
	}

	public int getNbArticles() {
		return _articles.size();
	}

	public List<NewsArticle> getList() {
		return _articles;
	}

	public String getTitle() {
		if (getNbArticles() == 0)
			return null;
		return getArticleByIndex(0).getSubject();
	}
	
	public String getFrom() {
		if (getNbArticles() == 0)
			return null;
		return getArticleByIndex(0).getSubject();
	}
}
